﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Snake {
    public class FoodManager : MonoBehaviour {
        public Transform[] molds;
        public Transform parentOfSweet;

        private List<Transform> sweetPool = new List<Transform>();

        private int sweetCount = 0;

        private float time = 0;
        private float maxTime = 0.05f;

        void Start() {

        }

        void Update() {
            time += Time.deltaTime;
            if (time > maxTime) {
                time = 0;
                //if (sweets.Count < 100) {
                //    newSweet();
                //}
                if (sweetCount < 200) {
                    newSweet();
                }
            }
        }

        private void newSweet() {
            if (sweetPool.Count == 0) {
                Transform mObject = Instantiate(molds[Random.Range(0, molds.Length)]) as Transform;
                mObject.parent = parentOfSweet;
                mObject.gameObject.SetActive(false);
                sweetPool.Add(mObject);
            }

            Transform mold = sweetPool[sweetPool.Count - 1];
            sweetPool.RemoveAt(sweetPool.Count - 1);
            mold.gameObject.SetActive(true);

            Camera camera = Camera.main;
            if (!camera)
                return;

            float h = camera.orthographicSize;
            float w = camera.aspect * h;
            mold.localPosition = new Vector3(Random.Range(-w, w), Random.Range(-h, h), 0);

            float scale = Random.Range(0.2f, 0.35f);
            mold.localScale = new Vector3(scale, scale, 1);
            
            sweetCount++;
        }

        public void RemoveSweet(Transform sweet) {
            sweetPool.Add(sweet);
            sweet.gameObject.SetActive(false);

            sweetCount--;
        }
    }
}